package cmd

import (
	"encoding/json"
	"errors"
	"fmt"
	"github.com/gookit/color"
	"github.com/spf13/cobra"
	"io/ioutil"
	"melon/server/global"
	"net/http"
	"net/url"
)

type Response struct {
	Msg  string `json:"msg"`
	Code string `json:"code"`
}

// versionCmd represents the version command
var updateCmd = &cobra.Command{
	Use:   "update",
	Short: "更新配置",
	Long:  `更新配置长信息`,
	Run: func(cmd *cobra.Command, args []string) {
		urlString := global.MelonYml.GetString("HttpClient.Url")
		domain := global.MelonYml.GetString("Qiniu.Domain")
		filename := global.MelonYml.GetString("Custom.LocalFilename")
		err := updateInfo(urlString, "android_apk_url", fmt.Sprintf("%s/%s", domain, filename))
		if err != nil {
			color.Error.Println("更新url失败")
			return
		}
		err = updateInfo(urlString, "android_app_version", global.MelonYml.GetString("Custom.Version"))
		if err != nil {
			color.Error.Println("更新version失败")
			return
		}
		err = updateInfo(urlString, "android_update_content", global.MelonYml.GetString("Custom.UpdateInfo"))
		if err != nil {
			color.Error.Println("更新info失败")
			return
		}
		err = updateInfo(urlString, "android_update_time", global.MelonYml.GetString("Custom.UpdateTime"))
		if err != nil {
			color.Error.Println("更新时间失败")
			return
		}
		err = updateInfo(urlString, "android_version_control", global.MelonYml.GetString("Custom.CompatibleVersion"))
		if err != nil {
			color.Error.Println("更新信息失败")
			return
		}
		color.Info.Println("更新信息成功")
	},
}

func init() {
	rootCmd.AddCommand(updateCmd)
}

func updateInfo(urlString, key, value string) error {
	params := url.Values{}

	Url, err := url.Parse(urlString)
	if err != nil {
		panic(err.Error())
	}
	params.Set("key", key)
	params.Set("val", value)
	Url.RawQuery = params.Encode()
	urlPath := Url.String()
	resp, err := http.Get(urlPath)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	s, err := ioutil.ReadAll(resp.Body)
	var a Response
	if err = json.Unmarshal(s, &a); err != nil {
		color.Error.Printf("Unmarshal err, %v\n", err)
		return err
	}
	if a.Code != "0" {
		return errors.New("fail")
	}
	return nil
}
